package com.isyscore.os.metadata.kettle.vis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.isyscore.os.metadata.enums.KettleDataFlowNodeGroupType;
import com.isyscore.os.metadata.enums.KettleDataFlowNodeType;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 插入或更新
 */
@ApiModel("插入更新组件")
@Data
@EqualsAndHashCode(callSuper = false)
public class InsertUpdateNode extends VisNode {
    @ApiModelProperty("输出表名")
    @NotBlank(message = "输出表名不能为空")
    private String tableName;
    @ApiModelProperty("数据库链接标识")
    @NotNull(message = "数据库链接标识不能为空")
    private Long dataSourceId;

    @ApiModelProperty("数据库名")
    @NotBlank(message="数据库名不能为空")
    private String databaseName;

    @ApiModelProperty("用于对比的字段列表")
    @NotEmpty(message = "用于对比的字段列表不能为空")
    @Valid
    List<FieldTuple> keyFieldMapping;


    @ApiModelProperty("用于更新的字段列表")
    @NotEmpty(message = "用于更新的字段列表不能为空")
    @Valid
    List<FieldTuple> updateFieldMapping;

    @ApiModelProperty("并行度")
    private Integer copies;

    @Override
    public void valueOf(Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject(params);
        this.tableName = jsonObject.getString("tableName");
        this.dataSourceId = jsonObject.getLong("dataSourceId");
        this.databaseName = jsonObject.getString("databaseName");
        this.keyFieldMapping = Optional.ofNullable(jsonObject.getJSONArray("keyFieldMapping")).orElse(new JSONArray()).stream().map(o ->
                JSON.parseObject(JSON.toJSONString(o), FieldTuple.class)).collect(Collectors.toList());
        this.updateFieldMapping = Optional.ofNullable(jsonObject.getJSONArray("updateFieldMapping")).orElse(new JSONArray()).stream().map(o ->
                JSON.parseObject(JSON.toJSONString(o), FieldTuple.class)).collect(Collectors.toList());
        setId(jsonObject.getString("id"));
        setNodeName(jsonObject.getString("nodeName"));

        this.copies = jsonObject.getInteger("copies");
    }

    public Long getDataSourceId() {
        return dataSourceId;
    }

    @Override
    public String getDatabaseName() {
        return databaseName;
    }
    @Override
    public KettleDataFlowNodeGroupType getGroupType() {
        return KettleDataFlowNodeGroupType.OUTPUTS;
    }

    @Override
    public KettleDataFlowNodeType getNodeType(){
        return KettleDataFlowNodeType.InsertUpdate;
    }

}
